import { Router } from 'express'
import { readFileSync } from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 读取学习主题数据
const subjectsData = JSON.parse(
  readFileSync(path.join(__dirname, '../../data/subjects.json'), 'utf8')
)

const router = Router()

/**
 * 获取所有练习分类
 * 根据学习主题自动生成练习分类
 */
router.get('/categories', (req, res) => {
  try {
    const { level, subject } = req.query

    let filteredSubjects = subjectsData.subjects

    // 如果指定了学段，进行过滤
    if (level) {
      filteredSubjects = filteredSubjects.filter(subject => subject.level === level)
    }

    // 如果指定了特定主题，只返回该主题的练习分类
    if (subject) {
      filteredSubjects = filteredSubjects.filter(subject => subject.id === subject)
    }

    // 为每个学习主题生成对应的练习分类
    const practiceCategories = filteredSubjects.map(subject => ({
      id: `${subject.id}-practice`,
      subjectId: subject.id,
      name: `${subject.name}练习`,
      description: `练习${subject.description}相关的题目`,
      icon: subject.icon,
      level: subject.level,
      difficulty: subject.difficulty,
      questionCount: Math.floor(Math.random() * 20) + 15, // 随机生成题目数量
      topics: subject.topics.map(topic => ({
        id: `${topic.id}-practice`,
        name: `${topic.name}练习`,
        description: topic.description,
        questionCount: Math.floor(Math.random() * 10) + 5
      })),
      estimatedTime: Math.floor(subject.estimatedTime * 0.8), // 练习时间约为学习时间的80%
      createdAt: subject.createdAt,
      updatedAt: new Date().toISOString()
    }))

    res.json({
      code: 200,
      data: practiceCategories,
      msg: '获取练习分类成功'
    })
  } catch (error) {
    console.error('获取练习分类失败:', error)
    res.status(500).json({
      code: 500,
      data: null,
      msg: '获取练习分类失败'
    })
  }
})

/**
 * 根据主题ID获取练习分类详情
 */
router.get('/categories/:categoryId', (req, res) => {
  try {
    const { categoryId } = req.params

    // 从categoryId中提取subjectId
    const subjectId = categoryId.replace('-practice', '')

    const subject = subjectsData.subjects.find(s => s.id === subjectId)

    if (!subject) {
      return res.status(404).json({
        code: 404,
        data: null,
        msg: '练习分类不存在'
      })
    }

    const practiceCategory = {
      id: `${subject.id}-practice`,
      subjectId: subject.id,
      name: `${subject.name}练习`,
      description: `练习${subject.description}相关的题目`,
      icon: subject.icon,
      level: subject.level,
      difficulty: subject.difficulty,
      questionCount: Math.floor(Math.random() * 20) + 15,
      topics: subject.topics.map(topic => ({
        id: `${topic.id}-practice`,
        name: `${topic.name}练习`,
        description: topic.description,
        questionCount: Math.floor(Math.random() * 10) + 5
      })),
      estimatedTime: Math.floor(subject.estimatedTime * 0.8),
      createdAt: subject.createdAt,
      updatedAt: new Date().toISOString()
    }

    res.json({
      code: 200,
      data: practiceCategory,
      msg: '获取练习分类详情成功'
    })
  } catch (error) {
    console.error('获取练习分类详情失败:', error)
    res.status(500).json({
      code: 500,
      data: null,
      msg: '获取练习分类详情失败'
    })
  }
})

/**
 * 获取练习分类的题目列表
 */
router.get('/categories/:categoryId/questions', (req, res) => {
  try {
    const { categoryId } = req.params
    const { topic, difficulty, count = 10 } = req.query

    // 从categoryId中提取subjectId
    const subjectId = categoryId.replace('-practice', '')

    const subject = subjectsData.subjects.find(s => s.id === subjectId)

    if (!subject) {
      return res.status(404).json({
        code: 404,
        data: null,
        msg: '练习分类不存在'
      })
    }

    // 这里应该从数据库获取实际的题目数据
    // 目前返回模拟数据
    const mockQuestions = Array.from({ length: parseInt(count) }, (_, index) => ({
      id: `question-${categoryId}-${index + 1}`,
      type: subjectId,
      topic: topic || subject.topics[0]?.id,
      difficulty: difficulty || subject.difficulty,
      question: `这是${subject.name}的第${index + 1}道练习题`,
      options: ['选项A', '选项B', '选项C', '选项D'],
      correctAnswer: '选项A',
      explanation: `这是${subject.name}练习题的详细解释`,
      createdAt: new Date().toISOString()
    }))

    res.json({
      code: 200,
      data: {
        list: mockQuestions,
        total: mockQuestions.length,
        category: {
          id: categoryId,
          name: `${subject.name}练习`,
          subjectId: subject.id
        }
      },
      msg: '获取练习题成功'
    })
  } catch (error) {
    console.error('获取练习题失败:', error)
    res.status(500).json({
      code: 500,
      data: null,
      msg: '获取练习题失败'
    })
  }
})

// 保留原有的练习记录相关API
router.get('/:userId/stats', (req, res) => {
  const { userId } = req.params
  // 这里应该从数据库获取用户数据
  // 目前返回模拟数据
  res.json({
    code: 200,
    data: {
      totalPractice: 0,
      averageScore: 0,
      totalTime: 0,
      subjectStats: {}
    },
    msg: '获取练习统计成功'
  })
})

router.post('/:userId', (req, res) => {
  const { userId } = req.params
  const practiceRecord = req.body
  // 这里应该保存到数据库
  res.json({
    code: 200,
    data: { id: Date.now().toString(), ...practiceRecord },
    msg: '练习记录保存成功'
  })
})

router.get('/:userId', (req, res) => {
  const { userId } = req.params
  // 这里应该从数据库获取用户数据
  res.json({
    code: 200,
    data: [],
    msg: '获取练习记录成功'
  })
})

export default router
